<template>
	<scroll-view scroll-y="true" class="container" :class="themeStyle">
		<view class="header-wrap" :class="themeStyle">
			<view class="logo-box">
				<image :src="$util.img(infos.logo)" mode="aspectFit"></image>
				<text>登录</text>
			</view>
			<view class="to-login">
				<text>还没有账号，立即</text><text class="login-text" @click="toReg()">注册</text>
			</view>
		</view>
		<view class="body-wrap"> 
			<view class="form-wrap">
				<view class="input-wrap">
					<view class="content"><input type="text" placeholder="请输入账号" placeholder-class="input-placeholder" class="input"
						 v-model="formData.account" /></view>
				</view>
				<view class="input-wrap">
					<view class="content"><input type="password" placeholder="请输入密码" placeholder-class="input-placeholder" class="input"
						 v-model="formData.password" /></view>
				</view>
				<view class="input-wrap">
					<view class="content">
						<input type="text" placeholder="请输入验证码" placeholder-class="input-placeholder" class="input" v-model="formData.vercode" />
						<image :src="captcha.img" mode="" class="captcha" @click="getCaptcha"></image>
					</view>
				</view>
				
			</view>
			<view class="forget-section">
				<view>
					<!-- <text @click="switchLoginMode" v-show="loginMode == 'mobile'">账号登录</text> -->
					<!-- <text @click="switchLoginMode" v-show="loginMode == 'account' && registerConfig.dynamic_code_login == 1">短信快捷登录</text> -->
				</view>
				<view class="align-right"><text @click="forgetPassword">忘记密码</text></view>
			</view>
			<!-- <view class="message-tips">
				<text>商城升级导致密码重置，如无法登录请选择"忘记密码"，通过短信重置您的登录密码</text>
			</view> -->
			<view class="login-btns auth-logins message-tip mars-top">商城升级导致密码重置，如无法登录请选择"忘记密码"，通过短信重置您的登录密码</view>
			<button type="default" @click="login" class="login-btn mar-top">登录</button>
			<button type="warn" @click="authLogin" v-if="isBind" class="auth-login text-color mar-top2 bod-color">一键授权登录</button>
			<!-- #ifdef MP -->
			<button open-type="getPhoneNumber" v-if="!isBind" class="auth-login ns-border-color" @getphonenumber="mobileAuthLogin">
				<text class="ns-text-color ns-border-color">一键授权登录</text>
				<!-- <text class="iconfont iconweixin"></text> -->
			</button>
			<!-- #endif -->
			<!-- #ifdef APP-PLUS -->
			<view class="third-login">
				<view class="third-icon" @click="oauthLogin('qq')" v-if="oauthConfig && oauthConfig.qq.is_open == 1">
					<image class="third-icon-img" :src="$util.img('upload/uniapp/login/auth/qq.png')" mode="widthFix"></image>
				</view>
				<view class="third-icon" @click="oauthLogin('weixin')" v-if="oauthConfig && oauthConfig.wechat.is_open == 1">
					<image class="third-icon-img" :src="$util.img('upload/uniapp/login/auth/weixin.png')" mode="widthFix"></image>
				</view>
				<view class="third-icon" @click="oauthLogin('apple')" v-if="$util.isIos(13) && oauthConfig && oauthConfig.apple.is_open == 1">
					<image class="third-icon-img" :src="$util.img('upload/uniapp/login/auth/apple.png')" mode="widthFix"></image>
				</view>
			</view>
			<!-- #endif -->
		</view>
	</scroll-view>
</template>

<script>
	import validate from 'common/js/validate.js';
	import auth from 'common/js/auth.js';
	import oauth from 'common/js/oauth.js';
	import globalConfig from '@/common/js/golbalConfig.js';
	export default {
		data() {
			return {
				loginMode: 'account',
				formData: {
					mobile: '',
					account: '',
					password: '',
					vercode: '',
					dynacode: '',
					key: ''
				},
				captcha: {
					id: '',
					img: ''
				},
				isSub: false, // 提交防重复
				back: '', // 返回页
				redirect: 'redirectTo', // 跳转方式
				openidIsExits: false,
				isBind: false,
				dynacodeData: {
					seconds: 120,
					timer: null,
					codeText: '获取动态码',
					isSend: false
				},
				registerConfig: {
					is_enable: 1
				},
				// logo图
				infos: {},
			};
		},
		mixins: [auth, oauth, globalConfig],
		onLoad(option) {
			let url = '';
			if (option.back) {
				url = decodeURIComponent(option.back);
				if(option.redirectMode){
					this.redirect = option.redirectMode;
				}
				Object.keys(option).forEach(function(key) {
					if (key != 'back') {
						if (url.indexOf('?') != -1) {
							url += '&' + key + '=' + option[key];
						} else {
							url += '?' + key + '=' + option[key];
						}
					}
				});
				this.back = url;
			}
			this.getCaptcha();
			// this.getRegisterConfig();

			if (uni.getStorageSync('authInfo')) {
				let data = uni.getStorageSync('authInfo');
				if (data.authInfo) this.authInfo = data.authInfo;
				if (data.userInfo) this.userInfo = data.userInfo;
				this.checkOpenidIsExits();
			}
		},
		onShow() {
			// 刷新多语言
			this.$langConfig.refresh();
		
			// #ifdef MP
			this.getCode(() => {
				if (Object.keys(this.authInfo).length) {
					this.$api.sendRequest({
						url: '/api/login/openidisexits',
						data: this.authInfo,
						success: res => {
							if (res.code >= 0 && res.data > 0) {
								this.isBind = true;
							}
						}
					});
				}
			});
			// #endif
			this.getUserInfo();
			// 获取网站信息
			this.getInfo()
		},
		methods: {
			toReg() {
				this.redirectToLink('/pages/login/register/user_type?back='+this.back);
			},	
			getInfo() {
				// 获取网站信息
				this.$api.sendRequest({
					url: '/api/website/info',
					success: res => {
						if (res.code == 0) {
							this.infos = res.data;
							// console.log('获取网站信息1' + this.infos.longitude);
							// console.log('获取网站信息2' + this.infos.latitude);
						}
					}
				});
			},

			//一键授权登录
			mobileAuthLogin(e) {
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					var data = {
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData
					};
					if (Object.keys(this.authInfo).length) {
						data[this.authInfo.auth_tag] = this.authInfo.auth_openid;
						//补充uinid
						data.wx_unionid = this.authInfo.wx_unionid;
					}
					if (this.userInfo.avatarUrl != '') data.headimg = this.userInfo.avatarUrl;
					if (uni.getStorageSync('source_member')) data.source_member = uni.getStorageSync('source_member');

					if (this.isSub) return;
					this.isSub = true;

					this.$api.sendRequest({
						url: '/api/login/mobileauth',
						data,
						success: res => {
							if (res.code >= 0) {
								uni.setStorage({
									key: 'token',
									data: res.data.token,
									success: () => {
										uni.removeStorageSync('loginLock');
										uni.removeStorageSync('unbound');
										uni.removeStorageSync('authInfo');
										if (this.back != '') {
											this.$util.redirectTo(this.back, {}, this.redirect);
										} else {
											this.$util.redirectTo('/pages/member/index/index', {}, this.redirect);
										}
									}
								});
							} else {
								this.isSub = false;
								this.$util.showToast({
									title: res.message
								});
							}
						},
						fail: res => {
							this.isSub = false;
							this.$util.showToast({
								title: 'request:fail'
							});
						}
					});
				}
			},
			/**
			 * 获取注册配置
			 */
			// getRegisterConfig() {
			// 	this.$api.sendRequest({
			// 		url: '/api/register/config',
			// 		success: res => {
			// 			if (res.code >= 0) {
			// 				this.registerConfig = res.data.value;
			// 				if (this.registerConfig.dynamic_code_login == 1) this.loginMode = 'mobile';
			// 				else 
			// 				this.loginMode = 'account';
			// 			}
			// 		}
			// 	});
			// },
			/**
			 * 切换登录方式
			 */
			// switchLoginMode() {
			// 	this.loginMode = this.loginMode == 'mobile' ? 'account' : 'mobile';
			// },
			/**
			 * 获取验证码
			 */
			getCaptcha() {
				this.$api.sendRequest({
					url: '/api/captcha/captcha',
					data: {
						captcha_id: this.captcha.id
					},
					success: res => {
						if (res.code >= 0) {
							this.captcha = res.data;
							this.captcha.img = this.captcha.img.replace(/\r\n/g, '');
						}
					}
				});
			},
			/**
			 * 去注册
			 */
			redirectToLink(url) {
				this.$util.redirectTo(url);
			},

			/**
			 * 忘记密码
			 */
			forgetPassword() {
				if (this.back)
					this.$util.redirectTo('/otherpages/login/find/find', {
						back: this.back
					});
				else this.$util.redirectTo('/otherpages/login/find/find');
			},
			/**
			 * 登录
			 */
			login() {
				if(this.formData.account.trim() == 0){
						uni.showToast({
							icon: 'none',
							title: '请输入账号'
						})
						return false;
				}
				if(this.formData.password.trim().length<6){
						uni.showToast({
							icon: 'none',
							title: '密码至少为6位'
						})
						return false;
				}
				if (this.loginMode == 'account') {
					var url = '/api/login/login';
					data = {
						username: this.formData.account,
						password: this.formData.password,
						type:0,
					};
				} else {
					var url = '/api/login/mobile',
						data = {
							mobile: this.formData.mobile,
							key: this.formData.key,
							code: this.formData.dynacode
						};
				}
				if (this.captcha.id != '') {
					data.captcha_id = this.captcha.id;
					data.captcha_code = this.formData.vercode;
				}
				if (Object.keys(this.authInfo).length) {
					data[this.authInfo.auth_tag] = this.authInfo.auth_openid;
				}
				if (this.userInfo.avatarUrl != '') data.headimg = this.userInfo.avatarUrl;
				if (uni.getStorageSync('source_member')) data.source_member = uni.getStorageSync('source_member');

				if (this.verify(data)) {
					if (this.isSub) return;
					this.isSub = true;
					this.$api.sendRequest({
						url,
						data,
						success: res => {
							if (res.code >= 0) {
								uni.setStorage({
									key: 'token',
									data: res.data.token,
									success: () => {
										uni.removeStorageSync('loginLock');
										uni.removeStorageSync('unbound');
										console.log(this, 132)
										if (this.back != '') {
											console.log('进来了');
											this.$util.redirectTo(this.back, {}, this.redirect);
										} else {
											this.$util.redirectTo('/pages/member/index/index', {}, this.redirect);
										}
									}
								});
							} else {
								this.isSub = false;
								this.getCaptcha();
								this.$util.showToast({
									title: res.message
								});
							}
						},
						fail: res => {
							this.isSub = false;
							this.getCaptcha();
						}
					});
				}
			},
			/**
			 * 登录验证
			 * @param {Object} data
			 */
			verify(data) {
				console.log(this.loginMode)
				let rule = [];
				// 手机号验证
				if (this.loginMode == 'mobile') {
					rule = [{
							name: 'mobile',
							checkType: 'required',
							errorMsg: '请输入手机号'
						},
						{
							name: 'mobile',
							checkType: 'phoneno',
							errorMsg: '请输入正确的手机号'
						}
					];
					if (this.captcha.id != '')
						rule.push({
							name: 'captcha_code',
							checkType: 'required',
							errorMsg: this.$lang('captchaPlaceholder')
						});
					rule.push({
						name: 'code',
						checkType: 'required',
						errorMsg: this.$lang('dynacodePlaceholder')
					});
				}

				// 账号验证
				if (this.loginMode == 'account') {
					rule = [{
							name: 'username',
							checkType: 'required',
							errorMsg: this.$lang('accountPlaceholder')
						},
						{
							name: 'password',
							checkType: 'required',
							errorMsg: this.$lang('passwordPlaceholder')
						}
					];
					if (this.captcha.id != '')
						rule.push({
							name: 'captcha_code',
							checkType: 'required',
							errorMsg: this.$lang('captchaPlaceholder')
						});
				}

				var checkRes = validate.check(data, rule);
				if (checkRes) {
					return true;
				} else {
					this.$util.showToast({
						title: validate.error
					});
					return false;
				}
			},
			/**
			 * 授权登录
			 */
			authLogin() {
				if (this.isSub) return;
				this.isSub = true;
				this.$api.sendRequest({
					url: '/api/login/auth',
					data: this.authInfo,
					success: res => {
						if (res.code >= 0) {
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success: () => {
									uni.removeStorageSync('loginLock');
									uni.removeStorageSync('unbound');
									uni.removeStorageSync('authInfo');
									if (this.back != '') {
										this.$util.redirectTo(this.back, {}, this.redirect);
									} else {
										this.$util.redirectTo('/pages/member/index/index', {}, this.redirect);
									}
								}
							});
						} else {
							this.isSub = false;
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: res => {
						this.isSub = false;
						this.$util.showToast({
							title: 'request:fail'
						});
					}
				});
			},
			/**
			 * 发送手机动态码
			 */
			sendMobileCode() {
				if (this.dynacodeData.seconds != 120) return;
				var data = {
					mobile: this.formData.mobile,
					captcha_id: this.captcha.id,
					captcha_code: this.formData.vercode
				};
				var rule = [{
						name: 'mobile',
						checkType: 'required',
						errorMsg: '请输入手机号'
					},
					{
						name: 'mobile',
						checkType: 'phoneno',
						errorMsg: '请输入正确的手机号'
					},
					{
						name: 'captcha_code',
						checkType: 'required',
						errorMsg: '请输入验证码'
					}
				];
				var checkRes = validate.check(data, rule);
				if (!checkRes) {
					this.$util.showToast({
						title: validate.error
					});
					return;
				}
				if (this.dynacodeData.isSend) return;
				this.dynacodeData.isSend = true;
				this.$api.sendRequest({
					url: '/api/login/mobileCode',
					data: data,
					success: res => {
						this.dynacodeData.isSend = false;
						if (res.code >= 0) {
							this.formData.key = res.data.key;

							if (this.dynacodeData.seconds == 120 && this.dynacodeData.timer == null) {
								this.dynacodeData.timer = setInterval(() => {
									this.dynacodeData.seconds--;
									this.dynacodeData.codeText = this.dynacodeData.seconds + 's后可重新获取';
								}, 1000);
							}
						} else {
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: () => {
						this.$util.showToast({
							title: 'request:fail'
						});
						this.dynacodeData.isSend = false;
					}
				});
			},
			checkOpenidIsExits() {
				if (Object.keys(this.authInfo).length) {
					uni.setStorage({
						key: 'authInfo',
						data: {
							authInfo: this.authInfo,
							userInfo: this.userInfo
						}
					});
					this.$api.sendRequest({
						url: '/api/login/openidisexits',
						data: this.authInfo,
						success: res => {
							if (res.code >= 0 && res.data > 0) {
								this.isBind = true;
							}
						}
					});
				}
			},
		},
		watch: {
			'dynacodeData.seconds': {
				handler(newValue, oldValue) {
					if (newValue == 0) {
						clearInterval(this.dynacodeData.timer);
						this.dynacodeData = {
							seconds: 120,
							timer: null,
							codeText: '获取动态码',
							isSend: false
						};
					}
				},
				immediate: true,
				deep: true
			}
		}
	};
</script>

<style lang="scss">
	@import '../public/css/common.scss';
</style>
